package com.iven.xie.es.controller;

import com.iven.xie.es.Application;
import com.iven.xie.es.entity.Result;
import com.iven.xie.es.entity.doc.ProductDocument;
import com.iven.xie.es.service.EsSearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author iven.xie
 * @version 1.0
 * @date 2020/02/28 18:15
 */
@Api(tags = "es-demo接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("api/es/demo")
public class DemoController {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Resource
    private EsSearchService esSearchService;

    @ApiOperation(value = "新增数据", notes = "新增数据")
    @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result create(@RequestBody ProductDocument productDocument) {
        logger.info("create " + productDocument.toString());
        esSearchService.save(productDocument);
        return new Result(HttpStatus.OK.value(), "新增成功");
    }

    @ApiOperation(value = "查询数据", notes = "查询数据")
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public Result<ProductDocument> find(@RequestParam("id") String id) {
        logger.info("Id " + id);
        ProductDocument one = esSearchService.getById(id);
        return new Result<ProductDocument>(HttpStatus.OK.value(), one);
    }

    @ApiOperation(value = "查询数据", notes = "查询数据")
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public Result<List<ProductDocument>> findAll() {
        logger.info("findAll");
        List<ProductDocument> list = esSearchService.getAll();
        return new Result<List<ProductDocument>>(HttpStatus.OK.value(), list);
    }

    @ApiOperation(value = "删除数据", notes = "请把该数据删除掉")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<String> delete(@RequestParam("id") String id) {
        logger.info("Id " + id);
        esSearchService.delete(id);
        return new Result(HttpStatus.OK.value(), "删除成功");
    }

    @ApiOperation(value = "删除所有数据", notes = "请把所有数据删除掉")
    @RequestMapping(value = "/deleteAll", method = RequestMethod.DELETE)
    public Result<String> deleteAll() {
        esSearchService.deleteAll();
        return new Result(HttpStatus.OK.value(), "删除成功");
    }
}
